package com.hfxt.controller;

import com.hfxt.constants.PayChannelEnum;
import com.hfxt.dto.MaintainOrderDto;
import com.hfxt.dto.ModelDto;
import com.hfxt.po.PayOrder;
import com.hfxt.service.MaintainOrderService;
import com.hfxt.service.ModelService;
import com.hfxt.service.PayOrderService;
import com.hfxt.utils.AliPayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/pay")
public class AliPayController {

    @Autowired
    private AliPayUtils aliPayUtils;

    @Autowired
    private MaintainOrderService maintainOrderService;

    @Autowired
    private ModelService modelService;

    @Autowired
    private PayOrderService payOrderService;

    @RequestMapping("/aliPay")
    @ResponseBody
    public String aliPay(String orderNo) throws Exception {
        //查询原始订单
        MaintainOrderDto maintainOrderDto = maintainOrderService.getByNo(orderNo);
        ModelDto modelDto = modelService.getById(maintainOrderDto.getModelId());
        //生成支付订单
        //PayOrder payOrder=payOrderService.save(maintainOrderDto, PayChannelEnum.ALIPAY,maintainOrderDto.getSubscription());
        PayOrder payOrder = payOrderService.save(maintainOrderDto, PayChannelEnum.ALIPAY, maintainOrderDto.getPrice());
        //去支付
        return aliPayUtils.pCPay(modelDto.getModelName(), payOrder.getPayNo(), maintainOrderDto.getPrice() + "");
    }

    @RequestMapping("/return")
    public String returnUrl(HttpServletRequest request) throws Exception {
        //1.验签
        Map<String, String[]> requestMap = request.getParameterMap();
        Map<String, String> params = new HashMap<String, String>();
        for (Map.Entry<String, String[]> entry : requestMap.entrySet()) {
            String mapKey = entry.getKey();
            String mapValue = entry.getValue()[0];
            params.put(mapKey, mapValue);
        }
        boolean flag = aliPayUtils.validateParam(params);

        maintainOrderService.finishPay(params.get("trade_no"), params.get("out_trade_no"), params.get("total_amount"));
        return "redirect:" + aliPayUtils.getSuccessurl();
    }

}
